let _Vue = null;

// 如何更改当前显示的组件的？ -- 见router-view中的render


export default class VueRouter {
  static install (Vue) {
    // 1. 判断当前插件是否已经被安装
    if (VueRouter.install.installed) {
      return;
    }

    VueRouter.install.installed = true;
    // 2. 把Vue构造函数记录到全局变量
    _Vue = Vue;
    // 3. 把创建Vue 实例时候传入的router对象注入到Vue实力上
    _Vue.mixin({
      beforeCreate () {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router;
          this.$options.router.init();
        }
      }
    })
  }

  constructor (options) {
    this.options = options;
    this.routeMap = {};
    this.data = _Vue.observable({
      current: '/' // 记录当前地址
    });

    // 做一下路由初始化
    if (this.options.mode === 'history') {
      this.data.current = window.location.pathname;
    } else if (this.options.mode === 'hash') {
      this.data.current = this._getHash(window.location.hash);
    }
  }

  init () {
    this.createRouteMap();
    this.initComponents(_Vue);
    this.initEvent();
  }

  // 遍历所有的路由规则，把路由规则解析成键值对的形式 存储到routeMap中
  createRouteMap () {
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component;
    })
  }
  // 创建router-link和router-view
  initComponents (Vue) {
    const self = this;

    Vue.component('router-link', {
      props: {
        to: String
      },
      render (h) {
        return h('a', {
          attrs: { href: this.to },
          on: { click: this.clickHandler }
        }, [ this.$slots.default ])
      },
      methods: {
        clickHandler (e) {
          e.preventDefault();
          if (self.options.mode === 'history') {
            history.pushState({}, '', this.to); // 更改地址栏内容，但是不发送请求
          } else if (self.options.mode === 'hash') {
            window.location.hash = this.to;
          }
          this.$router.data.current = this.to;
        }
      }
    });

    Vue.component('router-view', {
      render (h) {
        const component = self.routeMap[self.data.current]; // 因为data是响应式的，所以data.current更改后，这里就会发生变化

        return h(component);
      }
    })
  }

  // 监听浏览器历史的变化
  initEvent () {
    window.addEventListener('hashchange', (route) => {
      this.data.current = this._getHash(route.newURL);
    });

    window.addEventListener('popstate', () => {
      this.data.current = window.location.pathname;
    })
  }

  _getHash (newURL) {
    const index = newURL.indexOf('#');

    if (index < 0) return '';

    let hashRoute = newURL.slice(index + 1);
    const searchIndex = hashRoute.indexOf('?');
    if (searchIndex < 0) {
      const hashIndex = hashRoute.indexOf('#');
      if (hashIndex > -1) {
        hashRoute = decodeURI(hashRoute.slice(0, hashIndex)) + hashRoute.slice(hashIndex)
      } else {
        hashRoute = decodeURI(hashRoute)
      }
    } else {
      hashRoute = decodeURI(hashRoute.slice(0, searchIndex)) + hashRoute.slice(searchIndex)
    }

    return hashRoute;
  }
}

